import axios from 'axios';

export interface Filters {
    name: string;
    creator: string;
    begin_time: string;
    
  }
  
export interface MeetingItem {
    name: string;
    creator: string;
    status: number;
    content: string;
    begin_time: string;
    end_time: string;
    imageURL: string;
    enterprice_name: string;
    id: number;
  }

  interface BackResponse<T> {
    code: number;
    data: T;
    message: string;
    isOk: boolean;
    msg: string;
  }
  export const getMeetingList = async (): Promise<MeetingItem[]> => {
    const response = await axios.get<BackResponse<MeetingItem[]>>('http://localhost:9000/meeting/list');
    if (response.data.code === 0) {
      return response.data.data; // 返回会议列表数据
    } else {
      throw new Error(response.data.message || '获取会议列表失败');
    }
  };
  export const addMeeting = async (meeting: MeetingItem): Promise<string> => {
    const response = await axios.post<BackResponse<string>>('http://localhost:9000/meeting/add', meeting);
    if (response.data.code === 0) {
      return response.data.message; // 返回消息
    } else {
      throw new Error(response.data.message || '获取新闻列表失败');
    }
  }
  export const editMeeting = async (meeting: MeetingItem): Promise<void> => {
    const response = await axios.post<BackResponse<void>>('http://localhost:9000/meeting/update', meeting);
    
    if (response.data.code !== 0) {
      throw new Error(response.data.message || '编辑新闻失败');
    }
  }
  export const searchMeetings = async (meeting: Filters): Promise<MeetingItem[]> => {
    const response = await axios.post<BackResponse<MeetingItem[]>>('http://localhost:9000/meeting/search', meeting);
    if (response.data.code === 0) {
      return response.data.data; // 返回列表数据
    } else {
      throw new Error(response.data.message || '获取新闻列表失败');
    }
  }
  export const deleteMeeting = async(id: number): Promise<void>=> {
    const payload = { id: id };
    const response = await axios.post<BackResponse<void>>('http://localhost:9000/meeting/delete', payload);
    if (response.data.code !== 0) {
      throw new Error(response.data.message || '删除新闻失败');
    }
  }
  export const exportFile = async (): Promise<void> => {
    try {
      const response = await axios({
        url: 'http://localhost:9000/export/meeting',
        method: 'GET',
        responseType: 'blob',  // 重要：确保响应类型为 'blob'
      });
  
      // 创建一个下载链接并模拟点击，从而实现文件下载
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'Meeting.xlsx');  // 为下载的文件指定默认文件名
      document.body.appendChild(link);
      link.click();
  
      // 清理创建的URL和链接元素
      link.parentNode.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
      throw new Error('导出失败');
    }
  };